from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from django.contrib.auth.models import User

import logging

logger = logging.getLogger(__name__)

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(max_length=75)

    class Meta:
        model = User
        fields = ("username", "email",)

    def save(self, commit=True):
        logger.debug('Form save')
        user = super(RegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

class NickForm(forms.Form):
    current_username = forms.CharField()
    username = forms.CharField(required=False)
    password = forms.CharField(widget=forms.PasswordInput, label="Password")
    password1 = forms.CharField(widget=forms.PasswordInput, label="New password")
    password2 = forms.CharField(widget=forms.PasswordInput, label="Repeat new password")
    email = forms.EmailField(required=False)

class UserProfileForm(UserChangeForm):
    new_username = forms.CharField(max_length=75)
    confirm_password = forms.CharField(widget=forms.PasswordInput, label="Confirm password")
    current_password = forms.CharField(widget=forms.PasswordInput, label="Current password")

    class Meta:
        model = User
        fields = ('username', 'password', 'email')
        widgets = {
            'password': forms.PasswordInput(),
        }

    def clean(self):
        logger.debug('clean;')
        cleaned_data = super(UserProfileForm, self).clean()
        logger.debug('clean; cleaned data are %s', cleaned_data)
        if 'username' in self._errors:
            logger.debug('clean; username in errors')
            del self._errors['username']
        logger.debug('clean; cleaned data are %s', cleaned_data)
        return cleaned_data

    def save(self, commit=True):
        logger.debug('Form save')
        user = super(UserProfileForm, self).save(commit=False)
        logger.debug('Before changing username')
        user.username = self.cleaned_data["new_username"]
        if commit:
            user.save()
        return user

class AddPhrasesForm(forms.Form):
    day = forms.CharField(label="Day")
    phrases = forms.CharField(label="Phrases")
    phrases_of_day = forms.CharField(label="Phrases of day")
    categories = forms.CharField(label="Categories")

